<template>
  <div class="container pad-l-15 pad-r-15">
    <header-bg></header-bg>
    <!-- 顶部横线 -->
    <div class="header-line"></div>
    <div class="mar-t--4 mar-b-20 pad-t-10 bg-color-white content-area">
      <!-- 日 月选择按钮-->
      <van-sticky>
        <div class="pad-l-15 pad-r-15 pad-t-10 pad-b-10 select-btn-box flex flex-between bg-color-white" ref="selectBtnBox">
          <div class="flex">
            <div class="select-btn flex" @click="showDateType = !showDateType">
              <span class="font-11 mar-r-4">{{columns[columnIndex]}}</span>
              <van-icon name="play" size="10px" style="transform:rotate(90deg)"/>
            </div>
            <div class="select-btn mar-l-5 flex" @click="showSelectDate = !showSelectDate">
              <span class="font-11 mar-r-4">{{countForDate}}</span>
              <van-icon name="play" size="10px" style="transform:rotate(90deg)"/>
            </div>
          </div>
          <div class="font-12 font-color-6">
            共{{orderNum}}笔订单
          </div>
        </div>
      </van-sticky>
      <!-- 收入总额 -->
      <div class="font-w pad-l-15 pad-r-15 mar-t-10 mar-b-30">
        <span class="font-12">￥<span class="font-20 font-color-3">{{totalPrice}}</span></span>
      </div>
      <!-- 柱形图-->
      <div class="pad-l-15 pad-r-15">
        <span class="font-w font-15 font-color-3">收入对比</span>
        <scroll-view scroll-y="true" :style="{height: showScrollData ? '' : '160px'}" :scroll-into-view="intoViewId" class="mar-t-14">
          <div class="v-align-c mar-t-8" v-for="(item, index) of dateOrders" :key="index" :id="'go'+item.formatTime">
            <span class="font-11 font-color-6" v-text="showMonth? item.formatTime + '月': item.formatTime + '日'"></span>
            <div class="flex-item pad-l-10 pad-r-10" @click="changeData(item)">
              <div class="progress">
                <div class="progress-num v-align-c" :style="{width: item.percent ? item.percent+'%' : '',background:(showMonth && curMonth === item.formatTime) || (!showMonth && curDate === item.formatTime) ? '#7427FF' : '#A979FF'}">
                  <!-- <span class="font-10 font-white pad-l-6 pad-r-6" v-if="(showMonth && curMonth === item.formatTime) || (!showMonth && curDate === item.formatTime)">{{item.percent}}%</span> -->
                </div>
              </div>
            </div>
            <span class="font-12 font-color-9">{{item.orderPrice}}</span>
          </div>
        </scroll-view>
        <div class="mar-t-10 text-align-c" @click="showScrollData=!showScrollData">
          <van-icon name="play" size="14px" :style="{transform:'rotate('+ deg +')'}"/>
        </div>
      </div>
      <!-- 环形图 -->
      <div class="mar-t-20">
        <span class="font-w font-15 font-color-3 mar-l-15">带货渠道</span>
        <div v-show="showCanvas">
          <canvas canvas-id="ringCanvas" id="ring-canvas"></canvas>
        </div>
      </div>
      <!-- 交易订单列表 -->
      <div class="pad-l-10 pad-r-10 pad-t-30 pad-b-15">
        <van-sticky :offset-top="selectBtnBoxHeight">
          <div class="order-list flex flex-between">
            <div class="select-btn flex">
              <span class="font-11 mar-r-4">{{countForDate}}-交易订单</span>
            </div>
            <div class="select-btn mar-l-5 flex" @click="showOrderType=true">
              <span class="font-11 mar-r-4">{{orderType[orderTypeIndex]}}</span>
              <van-icon name="play" size="10px" style="transform:rotate(90deg)"/>
            </div>
          </div>
        </van-sticky>
        <div class="pad-t-5">
          <!-- 订单详情 -->
          <template v-if="incomeOrderList.length">
            <div class="flex flex-between" v-for="(item, index) of incomeOrderList" :key="index">
              <div class="flex mar-t-15">
                <div>
                  <img class="width-53 height-53 border-radius-5" :src="item.goodsImageUrl" alt="">
                </div>
                <div class="flex-col mar-l-7">
                  <div class="channel v-align-c">
                    <span class="font-12 font-color-6">渠道:</span>
                    <div class="width-14 height-14 flex mar-l-8 flex-center" :style="{background: item.iconbg, borderRadius: '4px'}">
                      <img v-if="fileSpace" class="width-12 height-12" :src="fileSpace + item.icon" alt="">
                    </div>
                    <span class="font-12 mar-l-6">{{item.orderNo}}</span>
                  </div>
                  <div class="font-12 font-color-6">
                    <span>顾客:</span>
                    <span class="mar-l-8">{{item.customerNickname}}/{{item.customerPhone}}</span>
                  </div>
                  <div class="font-12 font-color-6">
                    <span>数量:</span>
                    <span class="mar-l-8">{{item.goodsNum}}</span>
                  </div>
                </div>
              </div>
              <div class="align-c">
                <span class="font-15 font-color-3 font-w">+{{item.actualPrice}}</span>
                <span class="font-10 font-color-9">{{item.completeTime}}</span>
              </div>
            </div>
          </template>
          <div class="pad-b-30 font-12 font-color-9 text-align-c" v-else style="padding-top:170px">
            您还没有订单哦~
          </div>
        </div>
      </div>
    </div>

    <!-- 选择器 -->
      <van-action-sheet :show="showDateType" @close="showDateType = false">
        <van-picker :show-toolbar="true" :columns="columns" @confirm="changeDateType" @cancel="showDateType=false"/>
      </van-action-sheet>
      <van-action-sheet :show="showSelectDate" @close="showSelectDate = false">
        <van-datetime-picker
          :type="showMonth ? 'year-month' : 'date'"
          :value="currentDate"
          :min-date="minDate"
          :title="showMonth? '选择年月':'选择年月日'"
          :max-date="maxDate"
          @confirm="confirmDate"
        />
      </van-action-sheet>
      <van-action-sheet :show="showOrderType" @close="showOrderType = false">
        <van-picker :show-toolbar="true" :columns="orderType" @confirm="changeOrderType" @cancel="showOrderType=false"/>
      </van-action-sheet>
  </div>
</template>

<script>
import { Charts } from '@/utils/wxcharts'
import headerBg from '@/components/headerBg'
import {statIncome, pageIncomeOrder} from '@/api/personal'
export default {
  data() {
    return {
      ringCharts: null,
      devWidth: '',
      showDateType: false,
      showSelectDate: false,
      columns: ['日统计', '月统计'],
      currentDate: new Date().getTime(),
      columnIndex: 0,
      ringPosition: '',
      ringCanvasHeight: '',
      minDate: new Date(2020, 0, 1).getTime(),
      maxDate: new Date().getTime(),
      showMonth: false,
      countForDate: '',
      orderNum: 0, // 订单数
      totalPrice: 0, // 订单金额
      ringData: [], // 饼图数据
      dateOrders: [], // 收入对比数据
      currentPage: 1, // 交易订单当前页
      incomeOrderList: [], // 交易订单列表
      queryDate: '',
      curMonth: '',
      curDate: '',
      intoViewId: '',
      showOrderType: false, // 选择订单类型 弹窗是否显示
      orderType: ['全部类型', '微信', '抖音', '快手'],
      orderTypeIndex: 0,
      platformType: '', // 订单类型
      // showCanvas: true,
      showScrollData: false, // 是否展开收入对比
      selectBtnBoxHeight: ''
    }
  },
  components: { headerBg },
  onShow() {
    this.currentPage = 1
    this.platformType = ''
    this.incomeOrderList = []
    this.showScrollData = false
  },
  mounted() {
    this.init()
  },
  computed: {
    showCanvas() {
      if (this.showDateType || this.showSelectDate || this.showOrderType) {
        return false
      } else {
        return true
      }
    },
    deg() {
      return this.showScrollData ? '270deg' : '90deg'
    }
  },
  watch: {
    columnIndex(val) {
      // 切换日统计 月统计
      this.showMonth = val
      // 显示当前年月/年月日
      this.countForDate = this.showMonth ? this.$utils.formatTimeToDate(this.currentDate, 'YYmm') : this.$utils.formatTimeToDate(this.currentDate, 'YYmmdd')
      // 更新收入对比数据
      this.queryDate = this.showMonth ? this.$utils.formatTimeToDate(new Date(), 'yyyy-MM') : this.$utils.formatTimeToDate(new Date(), 'yyyy-MM-dd')
    },
    queryDate(val, oldval) {
      if (!oldval) return
      this.incomeOrderList = []
      this.pageIncomeOrder(val)
      this.statIncome(val)
    },
    currentDate(val) {
      // 更新收入对比数据
      this.curMonth = new Date(this.currentDate).getMonth() + 1
      this.curDate = new Date(this.currentDate).getDate()
      this.queryDate = this.showMonth ? this.$utils.formatTimeToDate(val, 'yyyy-MM') : this.$utils.formatTimeToDate(val, 'yyyy-MM-dd')
    }
  },
  methods: {
    test() {
      this.showDateType = !this.showDateType
    },
    init() {
      this.$pt.showLoading({title: '加载中...'})
      // 获取select-btn-box元素高度
      let query = wx.createSelectorQuery()
      query.select('.select-btn-box').boundingClientRect(rect => {
        this.selectBtnBoxHeight = rect.height
      }).exec()
      // 初始时间 (年月日 yy-mm-dd)
      this.queryDate = this.$utils.formatTimeToDate(new Date(), 'yyyy-MM-dd')
      this.curMonth = new Date().getMonth() + 1
      this.curDate = new Date().getDate()
      // 获取设备 屏幕信息
      const devInfo = wx.getSystemInfoSync()
      this.devWidth = devInfo.windowWidth
      // ringPosition 用于适配不同屏幕大小下的环形图
      if (this.devWidth >= 375) {
        this.ringPosition = this.devWidth / 2 - 35
        this.ringCanvasHeight = 300
      } else if (this.devWidth <= 360 && this.devWidth > 320) {
        this.ringPosition = this.devWidth / 2 - 25
        this.ringCanvasHeight = 280
      } else if (this.devWidth <= 320) {
        this.ringPosition = this.devWidth / 2 - 20
        this.ringCanvasHeight = 260
      }
      this.showMonth = this.columnIndex
      this.countForDate = this.showMonth ? this.$utils.formatTimeToDate(this.currentDate, 'YYmm') : this.$utils.formatTimeToDate(this.currentDate, 'YYmmdd')
      this.statIncome(this.queryDate)
      this.pageIncomeOrder(this.queryDate)
    },
    // 获取收入明细
    statIncome(queryDate) {
      this.$pt.showLoading({title: '加载中...'})
      this.showScrollData = false
      let data = {
        customerId: this.getCustomerId,
        queryDate: queryDate
      }
      statIncome(data).then(res => {
        this.ringData = []
        let result = res.data
        result.dateOrders.forEach((item, index) => {
          let _tempArr = item.completeTime.split('-')
          item.percent = parseInt(item.percent)
          item.orderPrice = item.orderPrice * 1 >= 1000 ? (item.orderPrice * 1 / 1000).toFixed(2) + 'k' : item.orderPrice * 1
          item.orderPrice = item.orderPrice * 1 >= 10000 ? (item.orderPrice * 1 / 1000).toFixed(2) + 'w' : item.orderPrice * 1
          this.$set(item, 'formatTime', _tempArr[_tempArr.length - 1] * 1)
        })
        this.dateOrders = result.dateOrders
        this.orderNum = result.orderNum
        this.totalPrice = result.totalPrice
        let platformsInfo = Object.keys(result.platforms)
        if (platformsInfo.length) {
          platformsInfo.forEach(item => {
            let name = ''
            switch (item) {
              case '0':
                name = '微信'
                break
              case '1':
                name = '抖音'
                break
              case '2':
                name = '快手'
                break
              case '4':
                name = '拼多多'
                break
            }
            if (item !== '4') {
              this.ringData.push({
                name: name,
                data: result.platforms[item]['platformTotalPrice'] * 1,
                stroke: false,
                orderNum: result.platforms[item]['orderNum'],
                percent: result.platforms[item]['percent']
              })
            }
          })
        } else {
          this.ringData.push({
            name: '微信',
            data: 0,
            orderNum: 0,
            percent: 0,
            stroke: false
          }, {
            name: '抖音',
            data: 0,
            orderNum: 0,
            percent: 0,
            stroke: false
          }, {
            name: '快手',
            data: 0,
            orderNum: 0,
            percent: 0,
            stroke: false
          })
        }
        this.intoViewId = ''
        this.intoViewId = this.showMonth ? `go${this.curMonth}` : `go${this.curDate}`
        this.getRingCharts()
        this.$pt.hideLoading()
      }).catch(() => {
        this.$pt.hideLoading()
      })
    },
    // 获取收入明细 分页
    pageIncomeOrder(queryDate) {
      this.$pt.showLoading({title: '加载中...'})
      this.showScrollData = false
      let data = {
        customerId: this.getCustomerId,
        queryDate: queryDate,
        size: 10,
        currentPage: this.currentPage,
        platformType: this.platformType
      }
      pageIncomeOrder(data).then(res => {
        res.data.records.forEach(item => {
          // 时间重新格式化
          let date = item.completeTime.split(' ')
          let m = new Date(date[0]).getMonth() + 1
          let d = new Date(date[0]).getDate()
          item.completeTime = `${m}/${d} ${date[1]}`
          // 获取渠道图标
          switch (item.externalPlatformType) {
            case 0:
              item.icon = '/images/anchor-wx-icon.png'
              item.iconbg = '#09BB07'
              break
            case 1:
              item.icon = '/images/dy-icon.png'
              item.iconbg = '#000'
              break
            case 2:
              item.icon = '/images/ks-icon.png'
              item.iconbg = '#FA9401'
              break
          }
          this.incomeOrderList.push(item)
          this.$pt.hideLoading()
        })
        // this.incomeOrderList = res.data.records
      }).catch(() => {
        this.$pt.hideLoading()
      })
    },
    // 获取环形图信息
    getRingCharts() {
      this.ringCharts = null
      const _that = this
      this.ringCharts = new Charts({
        animation: true,
        canvasId: 'ringCanvas',
        type: 'ring',
        extra: {
          ringWidth: 18,
          pie: {
            offsetAngle: -180
          }
        },
        series: _that.ringData,
        disablePieStroke: true,
        width: _that.devWidth || 345,
        sourceWidth: _that.ringPosition,
        height: _that.ringCanvasHeight
      })
      this.$pt.hideLoading()
    },
    // 选择'日统计'/ '月统计'
    changeDateType(e) {
      this.showDateType = false
      if (this.columnIndex === e.mp.detail.index) return
      this.columnIndex = e.mp.detail.index
      this.orderTypeIndex = 0
      this.currentDate = new Date().getTime()
    },
    changeData(item) {
      this.orderTypeIndex = 0
      this.platformType = ''
      if (this.showMonth) {
        this.curMonth = item.formatTime
      } else {
        this.curDate = item.formatTime
      }
      this.countForDate = this.showMonth ? this.$utils.formatTimeToDate(item.completeTime, 'YYmm') : this.$utils.formatTimeToDate(item.completeTime, 'YYmmdd')
      this.queryDate = item.completeTime
    },
    changeOrderType(e) {
      if (this.orderTypeIndex === e.mp.detail.index) {
        this.showOrderType = false
        return
      }
      this.incomeOrderList = []
      this.orderTypeIndex = e.mp.detail.index
      this.currentPage = 1
      this.platformType = !this.orderTypeIndex ? '' : this.orderTypeIndex - 1
      this.pageIncomeOrder(this.queryDate)
      this.showOrderType = false
    },
    confirmDate(e) {
      this.orderTypeIndex = 0
      this.currentDate = e.mp.detail
      this.curMonth = new Date(this.currentDate).getMonth() + 1
      this.curDate = new Date(this.currentDate).getDate()
      this.showSelectDate = false
      this.countForDate = this.showMonth ? this.$utils.formatTimeToDate(this.currentDate, 'YYmm') : this.$utils.formatTimeToDate(this.currentDate, 'YYmmdd')
    },
    changeInputDate(e) {
    }
  },
  onReachBottom() {
    if (this.incomeOrderList.length === 0 || this.incomeOrderList.length % 10 !== 0) return
    this.currentPage++
    this.pageIncomeOrder()
  }
}
</script>

<style lang="less" scoped>
.container{
  padding-top: 29.5rpx;
  box-sizing: border-box;
  .header-line {
    width: 710rpx;
    height: 20rpx;
    border: 6rpx solid #8650FF;
    background: #7427FF;
    margin: 0 auto;
    border-radius: 11rpx;
    box-sizing: border-box;
    position: relative;
    left: 50%;
    margin-left: -355rpx;
    z-index: -1;
  }
  .content-area {
    border-bottom-left-radius: 6px;
    border-bottom-right-radius: 6px;
    .progress {
      width:100%;
      // height:13px;
      height: 5px;
      background:#EFE9FF;
      position:relative;
      border-radius: 5px;
      .progress-num {
        height:100%;
        position:absolute;
        top:0;
        left:0;
        border-radius: 10px;
        &>span{
          background: #7427FF;
          margin-left: auto;
          height: 100%;
          display: flex;
          align-items: center;
          border-radius: 8px;
        }
      }
    }
  }
  .order-list {
      background: #F5F7F9;
      border-radius: 12rpx;
  }
  .select-btn-box,.order-list {
    box-sizing: border-box;
    .select-btn{
      background: #F5F7F9;
      padding: 5px 7px;
      border-radius: 12rpx;
    }
  }
  #ring-canvas {
    width: 100%;
    height: 300px;
    background: #fff;
  }
  .channel {
    &>span:nth-child(3) {
      color: #2FB8FF;
    }
    .icon-bg-dy {
      border-radius: 4px;
      background: #000;
    }
    .icon-bg-wx {
      border-radius: 4px;
      background: #09BB07;
    }
    .icon-bg-ks {
      border-radius: 4px;
      background: #FA9401;
    }
  }
  /deep/ .van-progress {
    height: 10px;
    background: #F5F7F9;
  }
}

</style>